<template>
  <div class="crm-dashboard">
    <el-row :gutter="20">
      <!-- 统计概览 -->
      <el-col :span="6" v-for="item in overviewData" :key="item.title">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" :style="{ color: item.color }">
              <el-icon><component :is="item.icon" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ item.value }}</div>
              <div class="stat-title">{{ item.title }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">
      <!-- 跟进趋势图表 -->
      <el-col :span="12">
        <el-card shadow="hover" header="跟进趋势">
          <div ref="followupChart" style="height: 300px"></div>
        </el-card>
      </el-col>

      <!-- 订单分析图表 -->
      <el-col :span="12">
        <el-card shadow="hover" header="订单分析">
          <div ref="orderChart" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">
      <!-- 待办事项 -->
      <el-col :span="12">
        <el-card shadow="hover" header="待办事项">
          <el-table :data="todoList" style="width: 100%">
            <el-table-column prop="type" label="类型" width="100">
              <template #default="{ row }">
                <el-tag :type="row.type === '审核' ? 'warning' : 'info'">
                  {{ row.type }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="title" label="标题" />
            <el-table-column prop="time" label="时间" width="120" />
            <el-table-column label="操作" width="80">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleTodo(row)">处理</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 最近跟进 -->
      <el-col :span="12">
        <el-card shadow="hover" header="最近跟进">
          <el-timeline>
            <el-timeline-item
              v-for="(item, index) in recentFollowups"
              :key="index"
              :timestamp="item.time"
              :type="item.type"
            >
              <div class="followup-item">
                <div class="customer-name">{{ item.customerName }}</div>
                <div class="followup-content">{{ item.content }}</div>
                <div class="followup-user">{{ item.userName }}</div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onUnmounted } from 'vue'
  import * as echarts from 'echarts'
  import { statsApi } from '@/api/crm'

  // 统计概览数据
  const overviewData = ref([
    { title: '总客户数', value: '0', icon: 'User', color: '#409EFF' },
    { title: '今日跟进', value: '0', icon: 'ChatDotRound', color: '#67C23A' },
    { title: '待审核订单', value: '0', icon: 'Document', color: '#E6A23C' },
    { title: '已合作客户', value: '0', icon: 'Star', color: '#F56C6C' },
  ])

  // 待办事项
  const todoList = ref<any[]>([])

  // 最近跟进
  const recentFollowups = ref<any[]>([])

  // 图表引用
  const followupChart = ref()
  const orderChart = ref()

  // 图表实例引用
  let followupChartInstance: echarts.ECharts | null = null
  let orderChartInstance: echarts.ECharts | null = null

  // 窗口大小调整处理函数
  const handleFollowupResize = () => followupChartInstance?.resize()
  const handleOrderResize = () => orderChartInstance?.resize()

  // 初始化数据
  const initData = async () => {
    try {
      // 获取统计概览
      const overviewRes = await statsApi.dashboard()
      if (overviewRes.code === 0) {
        const data = overviewRes.data
        overviewData.value = [
          { title: '总客户数', value: data.totalCustomers, icon: 'User', color: '#409EFF' },
          { title: '今日跟进', value: data.todayFollowups, icon: 'ChatDotRound', color: '#67C23A' },
          { title: '待审核订单', value: data.pendingOrders, icon: 'Document', color: '#E6A23C' },
          { title: '已合作客户', value: data.cooperatedCustomers, icon: 'Star', color: '#F56C6C' },
        ]
      }

      // 获取跟进趋势
      const trendRes = await statsApi.customerStats()
      if (trendRes.code === 0) {
        initFollowupChart(trendRes.data)
      }

      // 获取订单分析
      const orderRes = await statsApi.orderStats()
      if (orderRes.code === 0) {
        initOrderChart(orderRes.data)
      }

      // 获取待办事项
      const todosRes = await statsApi.getTodos()
      if (todosRes.code === 0) {
        todoList.value = todosRes.data
      }

      // 获取最近跟进记录
      const followupsRes = await statsApi.getRecentFollowups()
      if (followupsRes.code === 0) {
        recentFollowups.value = followupsRes.data
      }
    } catch (error) {
      console.error('初始化数据失败:', error)
    }
  }

  // 初始化跟进趋势图表
  const initFollowupChart = (data: any) => {
    followupChartInstance = echarts.init(followupChart.value)
    const option = {
      tooltip: {
        trigger: 'axis' as const,
      },
      legend: {
        data: ['拜访', '电话', '微信', '邮件'],
        top: '10%',
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: {
        type: 'category' as const,
        boundaryGap: false,
        data: data.dates,
      },
      yAxis: {
        type: 'value' as const,
      },
      series: [
        {
          name: '拜访',
          type: 'line' as const,
          data: data.visit,
        },
        {
          name: '电话',
          type: 'line' as const,
          data: data.phone,
        },
        {
          name: '微信',
          type: 'line' as const,
          data: data.wechat,
        },
        {
          name: '邮件',
          type: 'line' as const,
          data: data.email,
        },
      ],
    }
    followupChartInstance.setOption(option)

    // 添加响应式调整
    window.addEventListener('resize', handleFollowupResize)
  }

  // 初始化订单分析图表
  const initOrderChart = (data: any) => {
    orderChartInstance = echarts.init(orderChart.value)
    const option = {
      tooltip: {
        trigger: 'axis' as const,
        axisPointer: {
          type: 'shadow' as const,
        },
      },
      legend: {
        data: ['诉讼', '非诉'],
        top: '10%',
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: {
        type: 'category' as const,
        data: data.months,
      },
      yAxis: {
        type: 'value' as const,
      },
      series: [
        {
          name: '诉讼',
          type: 'bar' as const,
          data: data.litigation,
        },
        {
          name: '非诉',
          type: 'bar' as const,
          data: data.nonLitigation,
        },
      ],
    }
    orderChartInstance.setOption(option)

    // 添加响应式调整
    window.addEventListener('resize', handleOrderResize)
  }

  // 处理待办事项
  const handleTodo = (item: any) => {
    // 根据类型跳转到相应页面
    if (item.type === '审核') {
      // 跳转到审核页面
    } else {
      // 跳转到跟进页面
    }
  }

  onMounted(() => {
    initData()
  })

  // 组件卸载时清理图表资源和事件监听器
  onUnmounted(() => {
    // 清理跟进趋势图表
    if (followupChartInstance) {
      window.removeEventListener('resize', handleFollowupResize)
      followupChartInstance.dispose()
      followupChartInstance = null
    }

    // 清理订单分析图表
    if (orderChartInstance) {
      window.removeEventListener('resize', handleOrderResize)
      orderChartInstance.dispose()
      orderChartInstance = null
    }
  })
</script>

<style scoped>
  .crm-dashboard {
    padding: 20px;
  }

  .stat-card {
    margin-bottom: 20px;
  }

  .stat-content {
    display: flex;
    align-items: center;
  }

  .stat-icon {
    font-size: 48px;
    margin-right: 20px;
  }

  .stat-value {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 5px;
  }

  .stat-title {
    color: #909399;
    font-size: 14px;
  }

  .followup-item {
    padding: 5px 0;
  }

  .customer-name {
    font-weight: bold;
    margin-bottom: 5px;
  }

  .followup-content {
    color: #606266;
    margin-bottom: 5px;
  }

  .followup-user {
    color: #909399;
    font-size: 12px;
  }
</style>
